package com.nakanomay.zkcase1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author nakano_may丶
 * @date 2023/4/18
 * @Version 1.0
 * @description zk客户端代码
 */
public class DistributeClient
{
    private String connectString = "172.16.102.100:2181,172.16.102.135:2181,172.16.102.136:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zk = null;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException
    {
        DistributeClient client = new DistributeClient();
        // 1 获取zk连接
        client.getConnect();

        // 2 监听/servers下面节点的增加和删除
        client.getServerList();

        // 3 业余逻辑（睡觉）
        client.business();
    }

    private void business() throws InterruptedException
    {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServerList() throws InterruptedException, KeeperException
    {
        List<String> children = zk.getChildren("/servers", true);

        List<String> servers = new ArrayList<>();
        for (String child : children) {
            byte[] data = zk.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }

        // 打印
        System.out.println(servers);
    }

    private void getConnect() throws IOException
    {
        zk = new ZooKeeper(connectString, sessionTimeout, event -> {
            try {
                getServerList();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            catch (KeeperException e) {
                e.printStackTrace();
            }
        });
    }
}
